package com.aboo.frame.util.rocketmq;

import com.aboo.frame.config.rocketmq.MqProducer;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

@Slf4j
public class SendMqUtil {

	public static SendStatus sendMsg(MqMsg msg) {
		SendStatus status = null;
		DefaultMQProducer producer = MqProducer.MQ_PRODUCER;
		if (msg == null || producer == null) {
			return status;
		}
		String topic = msg.getTopic();
		String tag = msg.getTag();
		String body = msg.getBody();
		if (StringUtils.isAnyBlank(topic, tag, body)) {
			return status;
		}

		try {
			Message message = new Message(topic, tag, body.getBytes(RemotingHelper.DEFAULT_CHARSET));

			SendResult sendResult = producer.send(message, 2000L);
			log.info("MQ消息生产后返回结果：{}", JSONObject.toJSONString(sendResult));
			status = sendResult.getSendStatus();
		} catch (Exception e) {
			log.error("MQ消息生产消息失败", e);
		}

		return status;
	}

}
